module namespace search = "http://www.xmlproject.com/smi/lib/controller/search";

import module namespace rest = "http://expath.org/ns/http-client";
import module namespace json = "http://www.zorba-xquery.com/modules/json";
import module namespace base64 = "http://www.zorba-xquery.com/modules/base64";
import module namespace html = "http://www.zorba-xquery.com/modules/tidy";
import module namespace util = "http://www.zorba-xquery.com/zorba/util-functions";

declare namespace eBayNs="urn:ebay:apis:eBLBaseComponents";

(:~
 : this function gets search results for the given query string from ebay.
 : It returns an xml representation of the search results.
 
Sample: Basic Call
http://open.api.ebay.com/shopping?
callname=FindPopularItems&
appid=AnthonyA-e5d4-4569-b305-0cc685ea12d3&
responseencoding=XML&
siteid=77&
QueryKeywords=harry%20potter&
AvailableItemsOnly=true&
MaxEntries=10&
version=745
 
 : @param $query the plain unencoded search term to search for
 : @return returns a searchresult element containing the provider name and results
 :)
 
declare sequential function search:ebay($query as xs:string)
{

    let $searchstring := fn:encode-for-uri($query)
    let $ebayurl_part1 := "http://open.api.ebay.com/shopping?callname=FindPopularItems&amp;appid=AnthonyA-e5d4-4569-b305-0cc685ea12d3&amp;responseencoding=XML&amp;siteid=77&amp;QueryKeywords="
    let $ebayurl_part2 := "&amp;AvailableItemsOnly=true&amp;MaxEntries=10&amp;version=745"
    let $ebayurl_part3 := fn:concat($ebayurl_part1, $searchstring)
    let $ebayurl := fn:concat($ebayurl_part3, $ebayurl_part2)
            
    (: get the results :)
    let $searchstring := $query
    
    return
        <searchresult>
            <provider>eBay</provider>
            {
                let $hits := rest:send-request((), $ebayurl)[2]
                for $hit in $hits//eBayNs:Item
                let $title := $hit/eBayNs:Title/text()
                let $url := $hit/eBayNs:ViewItemURLForNaturalSearch
                let $price := concat("&lt;p>",$hit/eBayNs:ConvertedCurrentPrice/text(),"&lt;/p>")
                
                (: we use tidy to remove the encoded html tags (e.g. &lt;) in the google contents :)
                let $content := html:tidy($price)
                
                return <result title="{$title}" href="{$url}">{$content}</result>
            }
        </searchresult>
};


(:~
 : this function gets search results for a given query string from Amazon.
 : It returns an xml representation of the search results.
 :)
 
 (: TODO :)
declare function search:amazon($query as xs:string)
{
  
  (: prepare the search url :)
     
  let $amazonurl := "nothing"
  return 
    <searchresult>
        <provider>Amazon</provider>
            <result title="Result1" href="www.amazon.com">from Amazon</result>
            <result title="Result2" href="www.amazon.com">from Amazon</result>
    </searchresult>
};
